/**
 * Copyright (c) 快宝网络 kuaidihelp.com Co., Ltd. All Rights Reserved 禁止外泄以及用于其它的商业用途
 */

import { utils } from '@base/config';
import { removeStorage } from '@base/utils/storage';
import { isArray, isFunction } from 'lodash';
import { history } from 'umi';
import constants from './constants';
import request from './request';
import { showMessage, Toast } from './toast';

export interface UtilsConfig {
  loginPath?: string; // 登录页面路由，默认为/user/login
  iv?: string; // 加密向量，默认为通用配置
  loginExpired?: ({ code }: { code: number }) => Promise<boolean | string>; // 登录是否过期验证，默认code === 1011代表登录过期
  loginWhiteList?: string[];
  crypto?: {
    appId?: number;
    file?: string;
  };
}

/**
 * @descriptions 业务配置utils相关
 */
const { loginPath, iv, loginExpired, loginWhiteList } = utils || {};
export { loginPath, iv, loginExpired, loginWhiteList };

type Callback = (p: string) => string;
type ParamsApi = string | ((p: any) => Promise<any>);

interface LoginOptions {
  toast?: Toast;
  data?: any;
}

/**
 * @descriptions 运行
 */
async function runParamsApi(api: ParamsApi, data?: any): Promise<any> {
  if (isFunction(api)) {
    return await api(data);
  }
  return await request(api, { method: 'POST', data });
}

/**
 * @descriptions 退出登录
 */
export async function logout(api?: ParamsApi, callback?: Callback) {
  const { search, pathname } = history.location;
  if (pathname === loginPath) return; // 已经是登录页了，不再跳转
  if (api) {
    const { code } = await runParamsApi(api);
    if (code > 0) return;
  }
  removeStorage({ key: constants.STORAGE_USER_INFO });
  if (isArray(loginWhiteList)) {
    const loginWhiteListIndex = loginWhiteList.findIndex((item) => item === pathname);
    if (loginWhiteListIndex > -1) {
      history.replace(`${pathname}${search}`);
      return;
    }
  }
  const callbackPath = isFunction(callback) && callback(pathname);
  const path = callbackPath || `${loginPath}?redirect=${encodeURIComponent(pathname + search)}`;
  if (typeof path === 'string') {
    history.replace(path);
  }
}

/**
 * @descriptions 退出登录
 */
export async function login(api: ParamsApi, opts: LoginOptions): Promise<any> {
  const { data, toast } = opts;
  const res = await runParamsApi(api, data);
  const { code, msg } = res;
  if (code == 0) {
    const { query: { redirect } = {}, pathname } = history.location;
    showMessage(msg, 'success', toast);
    if (redirect && typeof redirect === 'string') {
      if (/^http:/.test(redirect)) {
        window.open(redirect, '_self');
      } else {
        history.replace(redirect);
      }
      return;
    }
    if (pathname === loginPath) {
      // 无redirect ，且在登录页跳转首页
      history.replace('/');
    }
  } else {
    showMessage(msg, 'error', toast);
  }
  return res;
}
